package servlet;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pojo.User;
import service.RegisterServiceImpl;
import verify.MyVerify;

public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private RegisterServiceImpl registerServiceImpl;
	private DateFormat dateFormat;
       
    public RegisterServlet() {
        super();
        registerServiceImpl = new RegisterServiceImpl();
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String uname = request.getParameter("uname");
		String sal = request.getParameter("sal");
		String birth = request.getParameter("birth");
		String sex = request.getParameter("sex");
		String verify = registerServiceImpl.verify(uname, sal, birth, sex);
		if (!verify.equals(MyVerify.SUCCESS)) {
			response.sendRedirect("error?info="+verify);
			return;
		}else{
			int se = Integer.parseInt(sex);
			boolean gender = se==0?false:true;
			try {
				User user = new User(null,uname,Double.parseDouble(sal),dateFormat.parse(birth),gender);
				System.out.println(new String(uname.getBytes(),"UTF-8"));
				String result = registerServiceImpl.register(user);
				if (result.equals("success")) {
					HttpSession session = request.getSession();
					session.setAttribute("user", user);
					request.getRequestDispatcher("info").forward(request, response);
				}else{
					response.sendRedirect("error?info="+result);
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
			
		
	}
}
